<template>
  <div>
    <div class="plan-item">
      <div class="column-title" :title="`已添加 ${editingSRKey===''?socialRelationListDatas.length: socialRelationListDatas.length - 1}人`"> 家庭成员 </div>
      <a-table :columns="socialRelationListColumns" :data-source="socialRelationListDatas" bordered :pagination="false" rowKey="key">
        <template v-for="col in socialRelationListEditableColumns" :slot="col.prop" slot-scope="text, record">
          <editable-cell :field="col.prop" :tagType="col.tagType" :dictCode="col.dictCode" :text="text" :editable="record.editable" :editingKey="editingSRKey"
            @change="(e) => onCellChange(e, record.key, col.prop, 'socialRelationList')"
            @blur="(e) => onCellBlur(e, record.key, col.prop, 'socialRelationList')"
            @onEdit="(e) => onEdit(record, 'socialRelationList')"
            @onSave="(e) => onSave(record, 'socialRelationList')"
            @onCancel="(e) => onCancel(record, 'socialRelationList')"
            @onDelete="(e) => onDelete(record, 'socialRelationList')"
          />
        </template>
      </a-table>
    </div>
    <div class="plan-item">
      <div class="column-title column-title-required" :title="`已添加 ${editingHGKey===''?helpGroupListDatas.length: helpGroupListDatas.length - 1}人`"> 帮扶小组 </div>
      <a-table :columns="helpGroupListColumns" :data-source="helpGroupListDatas" bordered :pagination="false" rowKey="key">
        <template v-for="col in helpGroupListEditableColumns" :slot="col.prop" slot-scope="text, record">
          <editable-cell :field="col.prop" :tagType="col.tagType" :dictCode="col.dictCode" :text="text" :editable="record.editable" :editingKey="editingHGKey"
            @change="(e) => onCellChange(e, record.key, col.prop, 'helpGroupList')"
            @blur="(e) => onCellBlur(e, record.key, col.prop, 'helpGroupList')"
            @onEdit="(e) => onEdit(record, 'helpGroupList')"
            @onSave="(e) => onSave(record, 'helpGroupList')"
            @onCancel="(e) => onCancel(record, 'helpGroupList')"
            @onDelete="(e) => onDelete(record, 'helpGroupList')"
          />
        </template>
      </a-table>
      <a-button block size="large" @click="handleAdd('helpGroupList')" :disabled="editingHGKey !== ''" style="margin-top:20px;"> +添加 </a-button>
    </div>
    <a-form-model layout="horizontal" ref="ruleForm" :model="addScheduleDTO" :rules="validatorRules" v-bind="formItemLayout">
      <div class="plan-item">
        <div class="column-title column-title-required"> 计划类型（必填） </div>
        <z-form-item :datas="fieldArr1" :form="addScheduleDTO" :rules="validatorRules" :gutter="0" />
      </div>
      <div class="plan-item">
        <div class="column-title column-title-required" :title="`已添加 ${editingAPKey===''?actionPlansDatas.length: actionPlansDatas.length - 1}条`">
          行动计划表（必填）
          <a-tooltip placement="topLeft" title="时间安排时段内，如有相关数据，系统会自动判定为已完成，反之则为未完成。">
            <a-icon type="exclamation-circle" />
          </a-tooltip>
        </div>
        <a-table :columns="actionPlansColumns" :data-source="actionPlansDatas" bordered :pagination="false" rowKey="key">
          <template v-for="col in actionPlansEditableColumns" :slot="col.prop" slot-scope="text, record">
            <editable-cell :field="col.prop" :tagType="col.tagType" :dictCode="col.dictCode" :text="text" :editable="record.editable" :editingKey="editingAPKey"
              @change="(e) => onCellChange(e, record.key, col.prop, 'actionPlans')"
              @blur="(e) => onCellBlur(e, record.key, col.prop, 'actionPlans')"
              @onEdit="(e) => onEdit(record, 'actionPlans')"
              @onSave="(e) => onSave(record, 'actionPlans')"
              @onCancel="(e) => onCancel(record, 'actionPlans')"
              @onDelete="(e) => onDelete(record, 'actionPlans')"
            />
          </template>
        </a-table>
        <a-button block size="large" @click="handleAdd('actionPlans')" :disabled="editingAPKey !== ''" style="margin-top:20px;"> +添加 </a-button>
      </div>
      <div class="plan-item">
        <div class="column-title"> 预计困难/风险及预案 </div>
        <z-form-item :datas="fieldArr2" :form="addScheduleDTO" :rules="validatorRules" :gutter="0" />
      </div>
      <div class="plan-item">
        <div class="column-title"> 资源保障 </div>
        <z-form-item :datas="fieldArr3" :form="addScheduleDTO" :rules="validatorRules" :gutter="0" />
      </div>
    </a-form-model>
  </div>
</template>
<script>
import EditableCell from './editableCell'

export default {
  mounted(){
    this.socialRelationListDatas = this.$globalRelation.messNum
    // console.log(this.$globalRelation.messNum);
  },
  components: { EditableCell },
  props: ['current', 'value'],
  data() {
    return {
      model: {},
      typeKey: "", // key
      editingSRKey: "", // 家庭成员-编辑的key
      editingHGKey: "", // 帮扶小组-编辑的key
      editingAPKey: "", // 行动计划表-编辑的key
      // 家庭成员-表头
      socialRelationListColumns: [
        { title: "关系", dataIndex: "socialRelation", width: 120,customRender: text => {
            return this.$options.filters.filterArray(text, this.dictOptions1, 'value', 'text')
          }
        },
        { title: "姓名", dataIndex: "name", width: 80 },
        { title: "性别", dataIndex: "sex", width: 80,customRender: text => { return this.$filterDictTextByCache('sex', text) } },
        { title: "身份证号", dataIndex: "identityCard", width: 150, },
        { title: "需帮扶事项", dataIndex: "assistanceMatters", width: 240, scopedSlots: { customRender: "assistanceMatters" }, },
        { title: "操作", width: 120, dataIndex: "action", scopedSlots: { customRender: "action" }, },
      ],
      // 家庭成员-可编辑的选项表头
      socialRelationListEditableColumns: [
        { title: "需帮扶事项", prop:'assistanceMatters', tagType: 'input'},
        { title: "操作", prop:'action'},
      ],
      // 帮扶小组-表头
      helpGroupListColumns: [
        { title: "成员类型", dataIndex: "memberType", width: 120, scopedSlots: { customRender: "memberType" }, },
        { title: "工作单位及职务或身份", dataIndex: "post", width: 200, scopedSlots: { customRender: "post" }, },
        { title: "姓名", dataIndex: "name", width: 120, scopedSlots: { customRender: "name" }, },
        { title: "身份证号", dataIndex: "identification", width: 200, scopedSlots: { customRender: "identification" }, },
        { title: "性别", dataIndex: "gender", width: 120, scopedSlots: { customRender: "gender" }, },
        { title: "年龄", dataIndex: "age", width: 120, scopedSlots: { customRender: "age" }, },
        { title: "联系方式", dataIndex: "telphone", width: 150, scopedSlots: { customRender: "telphone" }, },
        { title: "操作", width: 120, dataIndex: "action", scopedSlots: { customRender: "action" }, },
      ],
      // 帮扶小组-可编辑的选项表头
      helpGroupListEditableColumns: [
        { title: "成员类型", prop:'memberType', tagType: 'search-select'},
        { title: "工作单位及职务或身份", prop:'post', tagType: 'dict-select', dictCode: 'groupPost'},
        { title: "姓名", prop:'name', tagType: 'input'},
        { title: "身份证号", prop:'identification', tagType: 'input'},
        { title: "性别", prop:'gender', tagType: 'dict-select', dictCode: 'sex'},
        { title: "年龄", prop:'age', tagType: 'input'},
        { title: "联系方式", prop:'telphone', tagType: 'input'},
        { title: "操作", prop:'action'},
      ],
      // 行动计划表-表头
      actionPlansColumns: [
        { title: "计划时间", dataIndex: "planTime", width: 200, scopedSlots: { customRender: "planTime" }, },
        { title: "介入类型", dataIndex: "typeIntervention", width: 200, scopedSlots: { customRender: "typeIntervention" }, },
        { title: "任务量", dataIndex: "taskVolume", width: 200, scopedSlots: { customRender: "taskVolume" }, },
        { title: "操作", width: 120, dataIndex: "action", scopedSlots: { customRender: "action" } },
      ],
      // 行动计划表-可编辑的选项表头
      actionPlansEditableColumns: [
        { title: "计划时间", prop:'planTime', tagType: 'range-picker'},
        { title: "介入类型", prop:'typeIntervention', tagType: 'dict-select', dictCode: 'typeIntervention'},
        { title: "任务量", prop:'taskVolume', tagType: 'input'},
        { title: "操作", prop:'action'},
      ],
      // 家庭成员-数组集
      socialRelationListDatas: [],
      // socialRelationListCacheDatas: [],
      // 帮扶小组-数组集
      helpGroupListDatas: [],
      // helpGroupListCacheDatas: [],
      // 行动计划表-数组集
      actionPlansDatas: [],
      // actionPlansCacheDatas: [],
      // 计划类型、预计困难/风险及预案、资源保障-对象
      addScheduleDTO: {},
      dictOptions1: [
        { text:"夫妻", value:"1" },{ text:"父子", value:"2" },{ text:"父女", value:"3" },
        { text:"母子", value:"4" },{ text:"母女", value:"5" },{ text:"儿子", value:"6" },
        { text:"女儿", value:"7" },{ text:"兄弟", value:"8" },{ text:"兄妹", value:"9" },
        { text:"姐弟", value:"10" },{ text:"姐妹", value:"11" },{ text:"其他", value:"12" },
      ],
      columnsRules: {
        memberType:[ { required: true, message: '请选择成员类型' }],
        post:[ { required: true, message: '请选择工作单位及职务或身份' }],
        name:[ { required: true, message: '请输入姓名' }],
        identification:[ 
          { required: true, message: '请输入身份证号' },
          { reg: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号' },
        ],
        gender:[ { required: true, message: '请选择性别' }],
        age:[ { required: true, message: '请输入年龄' }],
        telphone:[ 
          { required: true, message: '请输入联系方式' },
          { reg: /^(\+86)?1[3456789]\d{9}$/, message: '请输入正确的联系方式' },
        ],
        planTime:[ { required: true, type: 'array', message: '请选择计划时间' }],
        typeIntervention:[ { required: true, message: '请选择介入类型' }],
        taskVolume:[ { required: true, message: '请输入任务量' }]
      },
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 18 }
      },
      fieldArr1: [
        {label: '计划类型', prop: 'planType', tagType: 'dict-select', dictOptions: [{ text: '帮扶计划', value:'1' }], disabled: true},
        {label: '帮扶类别', prop: 'helpCategory', tagType: 'dict-select', 
          dictOptions:[
            { text: '就业扶持', value:'1' },
            { text: '教育扶持', value:'2' },
            { text: '医疗扶持', value:'3' },
            { text: '其他扶持', value:'4' }
          ]
        },
        {label: '计划内容', prop: 'planContent', tagType: 'textarea'},
      ],
      fieldArr2: [
        {label: '预计困难/风险', prop: 'risk', tagType: 'textarea',},
        {label: '预案', prop: 'reservePlan', tagType: 'textarea'},
      ],
      fieldArr3: [
        {label: '投入资源', prop: 'inputResourses', tagType: 'textarea',},
        {label: '预算', prop: 'budget', tagType: 'textarea'},
      ],
      validatorRules: {
        planType:[ { required: true, message: '请选择计划类型' }],
        helpCategory:[ { required: true, message: '请选择帮扶类别' }],
        planContent:[ { required: true, message: '请输入计划内容' }]
      }
    };
  },
  computed: {
    getValue() {
      let value = this.value ? this.value : {}
      return value
    },
    datas() {
      let key =
        this.typeKey === 'socialRelationList'
          ? 'socialRelationListDatas'
          : this.typeKey === 'helpGroupList'
          ? 'helpGroupListDatas'
          : this.typeKey === 'actionPlans'
          ? 'actionPlansDatas'
          : ''
      return key
    },
    editingKey() {
      let key =
        this.typeKey === 'socialRelationList'
          ? 'editingSRKey'
          : this.typeKey === 'helpGroupList'
          ? 'editingHGKey'
          : this.typeKey === 'actionPlans'
          ? 'editingAPKey'
          : ''
      return key
    }
  },
  watch: {
    // 家庭成员
    socialRelationListDatas: {
      immediate: true,
      deep: true,
      handler(val) {
        console.log(val);
        this.$set(this.model, 'socialRelationList', val)
      }
    },
    // 帮扶小组
    helpGroupListDatas: {
      immediate: true,
      deep: true,
      handler(val) {
        if(Object.keys(this.model).length > 0 && this.model.groupId) {
          let groupId = this.model.groupId?this.model.groupId: ''
          val.forEach(item => { item.groupId = groupId })
        }
        this.$set(this.model, 'helpGroupList', val)
      }
    },
    // 行动计划表
    actionPlansDatas: {
      immediate: true,
      deep: true,
      handler(val) {
        this.$set(this.model, 'actionPlans', val)
      }
    },
    // 计划类型、预计困难/风险及预案、资源保障
    addScheduleDTO: {
      immediate: true,
      deep: true,
      handler(val) {
        if(Object.keys(this.model).length > 0 && this.model.helpPlanId) {
          let helpPlanId = this.model.helpPlanId?this.model.helpPlanId: ''
          this.$set(val, 'id', helpPlanId)
        }
        this.$set(this.model, 'addScheduleDTO', val)
      }
    },
    getValue: {
      immediate: true,
      deep: true,
      handler(val) {
        console.log('getValue',val)
        const jsonVal = JSON.parse(JSON.stringify(val))
        this.model = Object.assign({}, this.model, jsonVal)
        if(Object.keys(this.model).length > 0 && this.model.socialRelationList) {
          this.socialRelationListDatas = this.model.socialRelationList.map(v=> {
            return { ...v, key: v.id }
          })
          // console.log(this.socialRelationListDatas);
        }
        if(Object.keys(this.model).length > 0 && this.model.helpGroupList) {
          this.helpGroupListDatas = this.model.helpGroupList.map(v=> {
            return { ...v, key: v.id }
          })
        }
        if(Object.keys(this.model).length > 0 && this.model.addScheduleDTO) {
          this.addScheduleDTO = this.model.addScheduleDTO
          if(Object.keys(this.model.addScheduleDTO).length > 0 && this.model.addScheduleDTO.actionPlans) {
            this.actionPlansDatas = this.model.addScheduleDTO.actionPlans.map(v=> {
              return { ...v, key: v.id, planTime: v.planStartTime && v.planEndTime? [v.planStartTime, v.planEndTime]:[]}
            })
          }
        }
      }
    }
  },
  created() {
    this.$set(this.addScheduleDTO, 'planType', '1')
    // this.helpGroupListCacheDatas = this.helpGroupListDatas.map((item) => ({ ...item }));
  },
  methods: {
    
    handleAdd(type) {
      this.typeKey = type
      const newData = { key: 'add_' + Date.parse(new Date()).toString(), addtable: true }
      this[this.datas] = [...this[this.datas], newData];
      this.onEdit(newData, type);
    },
    onCellChange(value, key, column, type) {
      this.typeKey = type
      const newData = [...this[this.datas]];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        if(column==='planTime') {
          this.$set(target, 'planStartTime', value[0])
          this.$set(target, 'planEndTime', value[1])
        }
        this[this.datas] = newData;
      }
      this.inRegExp(value, column)
    },
    onCellBlur(value, key, column, type) {
      this.typeKey = type
      // this.inRegExp(value, column)
    },
    onEdit(record, type) {
      const { key } = record
      this.typeKey = type
      // const newData = [...this.helpGroupListDatas];
      // const target = newData.filter((item) => key === item.key)[0];
      // this.editingKey = key;
      // if (target) {
      //   target.editable = true;
      //   this.helpGroupListDatas = newData;
      // }
      // this.datas
      const newData = [...this[this.datas]];
      const target = newData.filter((item) => key === item.key)[0];
      this[this.editingKey] = key;
      if (target) {
        target.editable = true;
        this[this.datas] = newData;
      }
    },
    onSave(record, type) {
      const { key } = record
      // console.log(this.inRegExp(record))
      if(this.inRegExp(record)) return
      this.typeKey = type
      const newData = [...this[this.datas]];
      // console.log(newData)
      // const newCacheData = [...this.helpGroupListCacheDatas];
      const target = newData.filter((item) => key === item.key)[0];
      // console.log(target)
      // const targetCache = newCacheData.filter((item) => key === item.key)[0];
      if (target) {
      // if (target && targetCache) {
        delete target.editable;
        if (target.addtable) delete target.addtable;
        // console.log(target)
        // if (targetCache.addtable) delete targetCache.addtable;
        this[this.datas] = newData;
        // console.log(this.datas)
        // Object.assign(targetCache, target);
        // this.helpGroupListCacheDatas = newCacheData;
      }
      this[this.editingKey] = "";
    },
    onCancel(record, type) {
      const { key } = record
      this.typeKey = type
      const newData = [...this[this.datas]];
      const target = newData.filter((item) => key === item.key)[0];
      this[this.editingKey] = "";
      if (target) {
        Object.assign(
          target,
          // this.helpGroupListCacheDatas.filter((item) => key === item.key)[0]
        );
        delete target.editable;
        this[this.datas] = newData;
      }
    },
    onDelete(record, type) {
      const { key } = record
      const dataSource = [...this[this.datas]];
      this[this.datas] = dataSource.filter((item) => item.key !== key);
      this[this.editingKey] = "";
    },
    inRegExp(recordValue, column) {
      let editableColumns = this.typeKey+'EditableColumns'
      let bool = false
      // 单个事件校验
      if (column && this.columnsRules[column]) {
        let rules = this.columnsRules[column]
        let value = recordValue
        if(!value || (value && value.length===0)) {
          this.$message.error({content: rules[0].message, key: column, duration: 3})
          bool = true
        }
        if(value && rules.length>1 && !rules[1].reg.test(value)) {
          this.$message.error({content: rules[1].message, key: column, duration: 3})
          bool = true
        }
      }
      // 保存事件校验
      if(!column) {
        let record = recordValue, props = []
        const { key } = record
        for (const keys in record) {
          let rules = this.columnsRules[keys]
          if(record[keys] && rules && rules.length>1) {
            let b = rules[1].reg.test(record[keys])
            if(b) props.push(keys)
          } else if(record[keys] && (!rules || rules.length===1)) {
            props.push(keys)
          }
        }
        let data = this[editableColumns].filter(item => props.indexOf(item.prop) === -1) // 过滤不满足条件的值
        let title = data.map(v=> { if(v.prop !== 'action') { return v.title } }).filter(obj => obj !== undefined)
        if(title && title.length>0) {
          this.$message.error({content: title.toString()+'校验不通过，请完善有误的数据', key: editableColumns+key, duration: 3})
          bool = true
        }
      }
      return bool
    }
    // getObjectVal(arr) {
    //   this.helpGroupListDatas = arr.reduce((pre,cur)=>{
    //     let target = pre.find(e=>e.key == cur.key)
    //     if (target){
    //       Object.assign(target, cur)
    //     } else{
    //       pre.push(cur)
    //     }
    //     return pre
    //   }, this.helpGroupListDatas)
    //   // this.helpGroupListDatas = [...this.helpGroupListDatas, ...val];
    //   this.helpGroupListCacheDatas = this.helpGroupListDatas.map((item) => ({ ...item }));
    // }
  }
}
</script>
<style lang="less" scoped>
.plan-item{
  margin-bottom: 26px;
  padding-bottom: 26px;
  border-bottom: 1px #ccc dashed;
  &:last-child{
    border-bottom: 0;
  }
}
.column-title {
  margin-bottom: 20px;
  font-weight: bold;
  &.column-title-required {
    &::before {
      content: "*";
      color: #f5222d;
    }
  }
}
</style>
